﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License
// See the LICENSE file in the project root for more information.
// Maintainer: Argo Zhang(argo@live.ca) Website: https://www.blazor.zone

namespace BootstrapBlazor.Server.Components.Samples;

/// <summary>
/// CardUpload sample code
/// </summary>
public partial class UploadCards : IDisposable
{
    private bool _isMultiple = true;
    private bool _isDirectory = false;
    private bool _isDisabled = false;
    private bool _isUploadButtonAtFirst = false;
    private bool _showProgress = true;
    private bool _showZoomButton = true;
    private bool _showDeleteButton = true;
    private bool _showDownloadButton = true;

    private List<UploadFile> DefaultFormatFileList { get; } =
    [
        new() { FileName = "Test.xls" },
        new() { FileName = "Test.doc" },
        new() { FileName = "Test.ppt" },
        new() { FileName = "Test.mp3" },
        new() { FileName = "Test.mp4" },
        new() { FileName = "Test.pdf" },
        new() { FileName = "Test.cs" },
        new() { FileName = "Test.zip" },
        new() { FileName = "Test.txt" },
        new() { FileName = "Test.dat" }
    ];

    private List<UploadFile> Base64FormatFileList { get; } =
    [
        new() { FileName = "Test", PrevUrl = "" },
    ];

    private static long MaxFileLength => 5 * 1024 * 1024;
    private CancellationTokenSource? _token;

    private async Task OnCardUpload(UploadFile file)
    {
        if (file is { File: not null })
        {
            // 服务器端验证当文件大于 5MB 时提示文件太大信息
            if (file.Size > MaxFileLength)
            {
                await ToastService.Information(Localizer["UploadsFileTitle"], Localizer["UploadsFileError"]);
                file.Code = 1;
                file.Error = Localizer["UploadsFileError"];
            }
            else
            {
                // 模拟保存成功
                await Task.Delay(100);
                await SaveToFile(file);
                await ToastService.Success(Localizer["UploadsFileTitle"], $"{file.File!.Name} {Localizer["UploadsSuccess"]}");
            }
        }
    }

    private async Task SaveToFile(UploadFile file)
    {
        // Server Side 使用
        // Web Assembly 模式下必须使用 WebApi 方式去保存文件到服务器或者数据库中
        // 生成写入文件名称
        if (!string.IsNullOrEmpty(WebsiteOption.Value.WebRootPath))
        {
            var uploaderFolder = Path.Combine(WebsiteOption.Value.WebRootPath, "images", "uploader");
            file.FileName = $"{Path.GetFileNameWithoutExtension(file.OriginFileName)}-{DateTimeOffset.Now:yyyyMMddHHmmss}{Path.GetExtension(file.OriginFileName)}";
            var fileName = Path.Combine(uploaderFolder, file.FileName);

            _token ??= new CancellationTokenSource();
            try
            {
                var ret = await file.SaveToFileAsync(fileName, MaxFileLength, token: _token.Token);

                if (ret)
                {
                    // 保存成功
                    file.PrevUrl = $"{WebsiteOption.Value.AssetRootPath}images/uploader/{file.FileName}";
                }
                else
                {
                    var errorMessage = Localizer["UploadsSaveFileError"];
                    file.Code = 1;
                    file.Error = errorMessage;
                    await ToastService.Error(Localizer["UploadsFileTitle"], errorMessage);
                }
            }
            catch (OperationCanceledException)
            {

            }
        }
        else
        {
            file.Code = 1;
            file.Error = Localizer["UploadsWasmError"];
            await ToastService.Error(Localizer["UploadsFileTitle"], Localizer["UploadsWasmError"]);
        }
    }

    /// <summary>
    /// <inheritdoc/>
    /// </summary>
    public void Dispose()
    {
        if (_token != null)
        {
            _token.Cancel();
            _token.Dispose();
            _token = null;
        }
        GC.SuppressFinalize(this);
    }
}
